package com.fz.song.util;

import org.apache.log4j.Logger;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * 日期操作工具类
 * 
 * @author daybreak
 * 
 */
public class DateUtils {

	private static Logger logger = Logger.getLogger(DateUtils.class);

	public static int getMondayPlus() {
		Calendar cd = Calendar.getInstance();
		// 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
		int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1;
		// 因为按中国礼拜一作为第一天所以这里减1
		if (dayOfWeek == 1) {
			return 0;
		} else {
			return 1 - dayOfWeek;
		}
	}

	/**
	 * 获得下周星期一开始的截至日期
	 * 
	 * @return
	 */
	public static Date getNextSunday(int day) {
		int mondayPlus = getMondayPlus();
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 + (day - 1));
		Date monday = currentDate.getTime();
		// DateFormat df = DateFormat.getDateInstance();
		// String preMonday = df.format(monday);
		return monday;
	}

	/**
	 * 获取本周一
	 * 
	 * @return
	 */
	public static String getMondayOFWeek() {
		int mondayPlus = getMondayPlus();
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus);
		Date monday = currentDate.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String preMonday = sdf.format(monday);
		return preMonday;
	}

	/**
	 * 获取本周日
	 * 
	 * @return
	 */
	public static String getCurrentWeekday() {
		int mondayPlus = getMondayPlus();
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus + 6);
		Date monday = currentDate.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String preMonday = sdf.format(monday);
		return preMonday;
	}

	public static String converTime(long timeGap) {
		// long timeGap = currentSeconds - timestamp;// 与现在时间相差秒数
		String timeStr = null;
		// if (timeGap > 24 * 60 * 60) {// 1天以上
		// timeStr = timeGap / (24 * 60 * 60) + "天";
		// } else if (timeGap > 60 * 60) {// 1小时-24小时
		// timeStr = timeGap / (60 * 60) + "小时";
		// } else if (timeGap > 60) {// 1分钟-59分钟
		if (timeGap > 60) {
			timeStr = timeGap / 60 + "分钟";

		} else {
			timeStr = timeGap + "秒";
		}
		// } else {// 1秒钟-59秒钟
		// timeStr = "刚刚";
		// }
		return timeStr;
	}

	/**
	 * 获得下周星期日的日期
	 * 
	 * @return
	 */
	public static Date getNextSunday() {
		int mondayPlus = getMondayPlus();
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 + 6);
		Date monday = currentDate.getTime();
		// DateFormat df = DateFormat.getDateInstance();
		// String preMonday = df.format(monday);
		return monday;
	}

	/**
	 * 获得下周星期一的日期
	 * 
	 * @return
	 */
	public static Date getNextMonday() {
		int mondayPlus = getMondayPlus();
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus + 7);
		Date monday = currentDate.getTime();
		// DateFormat df = DateFormat.getDateInstance();
		// String preMonday = df.format(monday);
		return monday;
	}

	public static String formatDate(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

	public static Date getSimpleDayDate(String srcdate) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sdf.parse(srcdate);
		} catch (ParseException e) {
			return null;
		}
	}

	public static Date getSimplaDate(String srcdate) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			return sdf.parse(srcdate);
		} catch (ParseException e) {
			return null;
		}
	}

	public static String getSimplaDateToWord(String srcdate) {
		try {
			srcdate = srcdate.trim();
			SimpleDateFormat sdf = null;
			if (srcdate.length() == 10) {
				sdf = new SimpleDateFormat("yyyy-MM-dd");
			} else {
				sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			}

			DateFormat format1 = new SimpleDateFormat("yyyy年MM月dd日");
			return format1.format(sdf.parse(srcdate));
		} catch (ParseException e) {
			return null;
		}

	}

	/**
	 * 得到指定时间下几天的时间
	 *
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static String getNextSimple(String srcdate, int num) {
		Date date = getSimplaDate(srcdate);
		date.setDate(date.getDate() + num);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

	/**
	 * N年钱
	 *
	 * @param num
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static String getNextYearSimple(int num) {
		Date date = new Date();
		date.setYear(date.getYear() - num);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

	/**
	 * 根据当前时间计算月份
	 *
	 * @param type
	 *            1:过去 2：将来
	 * @param num
	 *            要处理的月份数
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static String getMonthSimple(int type, int num) {
		Date date = new Date();
		if (type == 1) {
			date.setMonth(date.getMonth() - num);
		} else if (type == 2) {
			date.setMonth(date.getMonth() + num);
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(date);
	}

	/**
	 * N周钱
	 *
	 * @param num
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static String getNextWeekSimple(int num) {
		Date date = new Date();
		date.setDate(date.getDay() + num);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

	/**
	 * 得到前几天的时间
	 *
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static String getAgoSimple(int num) {
		Date date = new Date();
		date.setDate(date.getDate() - num);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

	/**
	 * 得到下几天的时间
	 *
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static String getNextSimple(int num) {
		Date date = new Date();
		date.setDate(date.getDate() + num);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

	public static String fromatSimple(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

	public static String getTimeNowFormate() {
		DateFormat format1 = new SimpleDateFormat("yyyyMMdd");
		return format1.format(new Date());
	}

	// 获得没有时间秒的当前时间在后面加了个S
	public static String getTimeNows() {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		return format1.format(new Date());
	}

	public static String getTimeNow() {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format1.format(new Date());
	}

	/**
	 * 获取系统当前时间
	 *
	 * @return yyyy年MM月dd日HH:mm
	 */
	public static String getTimeNowsToMsg() {
		DateFormat format1 = new SimpleDateFormat("yyyy年MM月dd日HH:mm");
		return format1.format(new Date());
	}

	/**
	 * 获取系统当前时间
	 *
	 * @return yyyy年MM月dd日HH:mm
	 */
	public static String getTimeNowsToWord() {
		DateFormat format1 = new SimpleDateFormat("yyyy年MM月dd日");
		return format1.format(new Date());
	}

	/**
	 * 获取系统当前时间+num 小时
	 *
	 * @param num
	 *            小时数
	 * @return yyyy年MM月dd日HH:mm
	 */
	public static String getTimeNowsToMsg(int num) {
		DateFormat format1 = new SimpleDateFormat("yyyy年MM月dd日HH:mm");

		Date date = new Date();
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		ca.add(Calendar.HOUR_OF_DAY, num);

		return format1.format(ca.getTime());
	}

	

	/**
	 * 将yyyy-MM-dd HH:mm:ss格式的时间转换为yyyyMMddHHmmss格式
	 *
	 * @param normaldate
	 * @return
	 */
	public static String timeToPlainString(String normaldate) {
		try {

			DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = format1.parse(normaldate);
			format1 = new SimpleDateFormat("yyyyMMddHHmmss");
			return format1.format(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 将yyyy-MM-dd HH:mm:ss格式的时间转换为yyyyMMddHHmmss格式
	 *
	 * @param FINTIME
	 * @return
	 */
	public static String ConvertTime(String FINTIME) {
		try {

			DateFormat format1 = new SimpleDateFormat("yyyyMMddHHmmss");
			Date date = format1.parse(FINTIME);
			format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return format1.format(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 判断原时间是否早于当前时间
	 *
	 * @param check_time
	 * @return
	 * @throws Exception
	 */
	public static boolean CompareToCurrentTime(String check_time) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			long time = sdf.parse(check_time).getTime();
			long cur_time = System.currentTimeMillis();
			// System.out.println("流标时间："+time + " 当前时间："+cur_time);
			if (time <= cur_time) {
				return true;
			} else {
				return false;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 得到本月第一天
	 *
	 * @return
	 */
	public static String getMonthFirstDay() {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM");
		return format1.format(new Date()) + "-01";
	}

	/**
	 * 得到当前年份
	 *
	 * @return
	 */
	public static int getCurrentYear() {
		DateFormat format1 = new SimpleDateFormat("yyyy");
		return Integer.valueOf(format1.format(new Date()));
	}

	/**
	 * 给指定时间加上指定的天数
	 *
	 * @param starttime
	 *            起始时间 yyyy-MM-dd hh:mm:ss
	 * @param loanPeriod
	 *            要加的天数
	 * @return 起始时间增加指定天数以后的时间
	 */
	public static String timeAddDay(String starttime, int days) {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			return format1.format(addDays(format1.parse(starttime), days));
		} catch (NumberFormatException e) {
			return null;
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 给指定时间加上指定的天数
	 *
	 * @param starttime
	 *            起始时间 yyyy-MM-dd
	 * @param loanPeriod
	 *            要加的天数
	 * @return 起始时间增加指定天数以后的时间
	 */
	public static String timeAddDays(String starttime, int days) {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return format1.format(addDays(format1.parse(starttime), days));
		} catch (NumberFormatException e) {
			return null;
		} catch (ParseException e) {
			return null;
		}
	}

	public static Date addDays(Date targetDate, int days) {
		targetDate.setDate(targetDate.getDate() + days);
		return targetDate;
	}

	public static Date addMonths(Date targetDate, int months) {
		targetDate.setMonth(targetDate.getMonth() + months);
		return targetDate;
	}

	public static Date addYears(Date targetDate, int years) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(targetDate);
		cal.add(Calendar.YEAR, years);
		return cal.getTime();
	}

	/**
	 * 给指定时间加上指定的月数
	 *
	 * @param tradingStartTime
	 *            起始时间
	 * @param loanPeriod
	 *            要加的月数
	 * @return 起始时间增加指定月数以后的时间
	 */
	public static String timeAddMonthWithShort(String tradingStartTime, String loanPeriod) {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return format1.format(DateUtils.addMonths(format1.parse(tradingStartTime), Integer.parseInt(loanPeriod)));
		} catch (NumberFormatException e) {
			return null;
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 给指定时间加上指定的月数
	 *
	 * @param tradingStartTime
	 *            起始时间
	 * @param loanPeriod
	 *            要加的月数
	 * @return 起始时间增加指定月数以后的时间
	 */
	public static String timeAddMonth(String tradingStartTime, String loanPeriod) {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return format1.format(DateUtils.addMonths(format1.parse(tradingStartTime), Integer.parseInt(loanPeriod)));
		} catch (NumberFormatException e) {
			return null;
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 给指定时间加上指定的月数
	 *
	 * @param tradingStartTime
	 *            起始时间
	 * @param loanPeriod
	 *            要加的月数
	 * @return 起始时间增加指定月数以后的时间
	 */
	public static String timeAddYear(String tradingStartTime, String loanPeriod) {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return format1.format(DateUtils.addYears(format1.parse(tradingStartTime), Integer.parseInt(loanPeriod)));
		} catch (NumberFormatException e) {
			return null;
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 根据字符串时间得到时间戳
	 * 
	 * @param start_time
	 * @return
	 */
	public static long getTimeMillis(String target_time) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sdf.parse(target_time).getTime();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("根据字符串时间得到时间戳，失败");
		}
	}

	/**
	 * 将简单时间格式字符串转换为Date
	 * 
	 * @param textDate
	 *            指定时间
	 * @return
	 */
	public static Date textDateToDate(String textDate) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			return sdf.parse(textDate);
		} catch (Exception e) {
			logger.error("指定时间转换为(yyyy-MM-dd)型值失败，参数为:" + textDate, e);
			return null;
		}
	}

	/**
	 * 得到当前时间到指定时间的天数间隔
	 * 
	 * @param target_time
	 *            指定时间
	 * @return 间隔天数 int型值
	 */
	public static int getTimeInterval(String target_time) {
		target_time = target_time.split(" ")[0];
		Date temp_date = textDateToDate(target_time);
		int days = (int) ((temp_date.getTime() - System.currentTimeMillis()) / (24 * 60 * 60 * 1000));
		return days + 1;// 都不能整除，需要加1
	}

	/**
	 * 得到开始时间到指定时间的天数间隔
	 * 
	 * @param target_time
	 *            指定时间
	 * @return 间隔天数 int型值
	 */
	public static Integer getTimeInterval(String start_time, String target_time) {
		target_time = target_time.split(" ")[0];
		Date start_date = textDateToDate(start_time.split(" ")[0]);
		Date temp_date = textDateToDate(target_time);
		int days = (int) ((temp_date.getTime() - start_date.getTime()) / (24 * 60 * 60 * 1000));

		return days + 1;// 都不能整除，需要加1
	}

	/**
	 * 计算两个日期之间相差的月数
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int getMonths(String start_time, String target_time) {
		int iMonth = 0;
		try {
			Date date1 = textDateToDate(start_time.split(" ")[0]);
			Date date2 = textDateToDate(target_time.split(" ")[0]);

			Calendar cal = Calendar.getInstance();
			cal.setTime(date1);
			int year1 = cal.get(Calendar.YEAR);
			int month1 = cal.get(Calendar.MONTH);

			cal.setTime(date2);
			int year2 = cal.get(Calendar.YEAR);
			int month2 = cal.get(Calendar.MONTH);

			if (year1 == year2) {
				iMonth = month2 - month1;
				if (month2 == month1) {
					iMonth = 1;
				}
			} else {
				iMonth = 12 * (year2 - year1) + month2 - month1;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return iMonth;
	}

	/**
	 * 判断传入日期是否在当前月
	 * 
	 * @param day
	 * @return
	 */
	public static boolean compareDayToMonth(String strStartDate, String strEndDate, String strNowDate) {
		Date startDate = textDateToDate(strStartDate);
		Date endDate = textDateToDate(strEndDate);
		Date nowDate = textDateToDate(strNowDate);

		if (startDate.compareTo(nowDate) == 0) {
			return true;
		}

		Calendar calBegin = Calendar.getInstance();
		calBegin.setTime(startDate);

		while (endDate.after(calBegin.getTime())) {
			// 根据日历的规则，为给定的日历字段添加或减去指定的时间量
			calBegin.add(Calendar.DAY_OF_MONTH, 1);
			// System.out.println( calBegin.getTime() );

			if (calBegin.getTime().compareTo(nowDate) == 0) {
				return true;
			}
		}

		return false;
	}

	/**
	 * 24:00:00根据时间返回秒
	 * 
	 * @author zhanghui
	 * @time 2016-2-22下午1:55:13
	 * @param time
	 * @return
	 */
	public static int getSecondsWithStr(String time) {
		String[] strs = time.split(":");
		int num = 0;
		if (strs.length == 3) {
			num += Integer.parseInt(strs[0]) * 60 * 60;
			num += Integer.parseInt(strs[1]) * 60;
			num += Integer.parseInt(strs[2]);
			return num;
		} else {
			return -1;
		}
	}

	/**
	 * 秒转化成时间
	 * 
	 * @author zhanghui
	 * @time 2016-2-22下午2:44:16
	 * @param s
	 * @return
	 */
	public static String getTimeWithSeconds(int s) {
		String ss = "";
		Integer hours = (int) (s / (60 * 60));
		Integer minutes = (int) (s / 60 - hours * 60);
		Integer seconds = (int) (s - minutes * 60 - hours * 60 * 60);
		System.out.println(hours);
		System.out.println(minutes);
		System.out.println(seconds);
		ss += hours < 10 ? "0" + hours + ":" : hours + ":";
		ss += minutes < 10 ? "0" + minutes + ":" : minutes + ":";
		ss += seconds < 10 ? "0" + seconds : seconds + "";
		return ss;
	}

	/**
	 * 两个时间差
	 * 
	 * @author zhanghui
	 * @time 2016-5-9下午8:34:01
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public static String getSubTwoDate(String startTime, String endTime) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d1 = null;
		Date d2 = null;
		try {
			d1 = format.parse(startTime);
			d2 = format.parse(endTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		long diff = d2.getTime() - d1.getTime();
		long diffSeconds = diff / 1000 % 60;
		long diffMinutes = diff / (60 * 1000) % 60;
		long diffHours = diff / (60 * 60 * 1000) % 24;
		return diffHours + ":" + diffMinutes + ":" + diffSeconds;
	}

	public static String secToTime(int time) {
		String timeStr = null;
		int hour = 0;
		int minute = 0;
		int second = 0;
		if (time <= 0)
			return "00:00";
		else {
			minute = time / 60;
			if (minute < 60) {
				second = time % 60;
				timeStr = unitFormat(minute) + "分" + unitFormat(second)+"秒";
			} else {
				hour = minute / 60;
				if (hour > 99)
					return "99时59分59秒";
				minute = minute % 60;
				second = time - hour * 3600 - minute * 60;
				timeStr = unitFormat(hour) + "时" + unitFormat(minute) + "分" + unitFormat(second)+"秒";
			}
		}
		return timeStr;
	}

	public static String unitFormat(int i) {
		String retStr = null;
		if (i >= 0 && i < 10)
			retStr = "0" + Integer.toString(i);
		else
			retStr = "" + i;
		return retStr;
	}

	public static void main(String[] args) {
		// DateUtils.getTimeNowsToMsg(3);
		System.out.println(DateUtils.secToTime(651));
	}

}
